package component.security.util;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;


import component.security.encrypt.Crypto;
import component.security.encrypt.Util;

/**
 * 加密解密管理类
 */

public class EncryptSecurityManager {
	
	
	//唯一实例
	private static EncryptSecurityManager instance = new EncryptSecurityManager();
	
	//是否有效
	private boolean isValidate = false;
	
	//存储Lience对
	private Map hash = new HashMap();
	
	//初始化函数
	private void init(){
		
		
		try{			
	
			//获取明文			
			Object obj = FileUtil.readObjectFromFile(FileUtil.getFileDir(Constant.LIENCE_OBJ_FILE));
			String pubStr = new String(obj.toString().getBytes(),"UTF-8");
			
			//获取密文
			byte[] cryptoByte = FileUtil.readByteFromFile(FileUtil.getFileDir(Constant.LIENCE_CRYPTO_FILE) );
			
			//获取公钥
			PublicKey publicKey = Util.getPublicKeyFromFile(FileUtil.getFileDir(Constant.PUBKEY_FILE));
			
			//对密文解密
			byte[] result = new Crypto().decrypt(cryptoByte,publicKey);
			String cryptoContent = new String(new String(result).getBytes(),"UTF-8");
			
			//判断是否有效		
			if (pubStr.equals(cryptoContent)){
				isValidate =true;
				
				//解析内容到hash
				String[] arrContent = cryptoContent.split(Constant.ROWSPLIT_STRING);
				String[] arrTemp;
				String strTemp;
				for (int ii=0; ii< arrContent.length; ii++){
					strTemp = arrContent[ii];
					if (!strTemp.equals("")){
						arrTemp = strTemp.split("=");
						hash.put(arrTemp[0],arrTemp[1]);
					}
				}
			}
			
			System.out.println("验证完成.........\n");	
		} catch (Exception ex){	
			ex.printStackTrace();
			isValidate = false;
		}
		
	}
	
	
	//构造函数初始化
	public  EncryptSecurityManager(){
		init();
				
	}
	
	/**
	 * 获取唯一实例
	 * @preserve
	 * @return
	 */
	public static EncryptSecurityManager getInstance(){
		return instance;
	}
		
	/**
	 * 检查明文和密文是否正确
	 *    即用户是否有效
	 * @preserve
	 * @return
	 */
	public  boolean checkUserValidate(){
		return isValidate;
		
	}
	
	/**
	 * 根据Key获取证书内容
	 * @preserve
	 * @param key
	 * @return
	 */
	public Object getValue(String key){
		if(checkUserValidate()){
			return hash.get(key);
		} else {
			return null;
		}		
	}
	
	
	/**
	 * @preserve
	 * @param args
	 */
	public static void main(String[] args){
		System.out.println("开始验证.........\n");
		System.out.print("是否合法：" + EncryptSecurityManager.getInstance().checkUserValidate());
		System.out.print("单位名称：" + EncryptSecurityManager.getInstance().getValue("UnitNamed"));
		System.out.print("用户数：" + EncryptSecurityManager.getInstance().getValue("UserNum"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try {
			br.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
